package com.bdqn.ch07.config.shiro;

import com.bdqn.ch07.entity.Right;
import com.bdqn.ch07.entity.Role;
import com.bdqn.ch07.entity.User;
import com.bdqn.ch07.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public class MyShiroRealm extends AuthorizingRealm {

    @Resource
    UserService userService;


    @Resource
    private StringRedisTemplate stringRedisTemplate;
    //redis 中数据的 key 的前缀
    private String SHIRO_LOGIN_COUNT = "shiro_login_count_"; //登录计数
    private String SHIRO_IS_LOCK = "shiro_is_lock_"; //锁定用户登录

    //shiro授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("调用 MyShiroRealm.doGetAuthorizationInfo 获取权限信息！");
        //获得权限信息
        User user = (User) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //静态授权：授予主体(用户)相应的角色和权限
        // info.addRole(user.getRole().getRoleName());//添加用户角色到info对象
        // info.addStringPermission("用户列表");//所有用户拥有"用户列表"权限
        // if ("管理员".equals(user.getRole().getRoleName())) {//管理员拥有"增删改"权限
        //     info.addStringPermission("用户添加");
        //     info.addStringPermission("用户编辑");
        //     info.addStringPermission("用户删除");
        // }

        //动态授权
        Role role = user.getRole();
        if (role != null) {
            info.addRole(user.getRole().getRoleName());
            Set<Right> rights = role.getRights();
            if (rights != null && rights.size() > 0) {
                for (Right right : rights) {
                    info.addStringPermission(right.getRightCode());
                }
            }
        }
        return info;
    }

    //shiro认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("调用 MyShiroRealm.doGetAuthenticationInfo 获取身份信息！");
        //获得身份信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String usrName = token.getUsername();
        User user = userService.findByUserNameBiz(usrName);

        //每次访问，登录次数+1,无论你登录是否成功都会+1
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        opsForValue.increment(SHIRO_LOGIN_COUNT + usrName, 1);
        //计数大于 3 时，设置用户被锁定一小时，清空登录计数
        if (Integer.parseInt(opsForValue.get(SHIRO_LOGIN_COUNT + usrName)) > 3) {
            opsForValue.set(SHIRO_IS_LOCK + usrName, "LOCK");
            //设置帐号锁定一个小时
            stringRedisTemplate.expire(SHIRO_IS_LOCK + usrName, 1, TimeUnit.HOURS);
            //清空登录计数
            stringRedisTemplate.delete(SHIRO_LOGIN_COUNT + usrName);
        }
        //判断帐号是否锁定，如果锁定抛出异常
        if ("LOCK".equals(opsForValue.get(SHIRO_IS_LOCK + usrName))) {
            throw new LockedAccountException();
        }

        if (user == null) {
            throw new UnknownAccountException(); //账号错误
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                user,//身份(根据用户名查询数据库获得的用户)
                user.getUsrPassword(),//凭证(查询数据库获得的密码)
                ByteSource.Util.bytes("czkt"), //加密使用的 salt
                getName()//Realm 对象的名称
        );
        //返回身份信息
        return info;
    }
}
